/*
 * @Author: your name
 * @Date: 2022-01-06 19:33:07
 * @LastEditTime: 2022-01-15 11:23:19
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \vue_test\src\router\index.js
 */
//该文件专门用于创建整个应用的路由器
import VueRouter from "vue-router";
//引入组件
import About from "../pages/About";
import Home from "../pages/Home";
import News from "../pages/News";
import Message from "../pages/Message";
import Detail from "../pages/Detail";

//创建一个路由器
const router = new VueRouter({
  routes: [
    {
      name: "guanyu",
      path: "/about",
      component: About,
      meta: { title: "关于" },
    },
    {
      name: "zhuye",
      path: "/home",
      component: Home,
      meta: { title: "主页" },
      children: [
        {
          name: "xinwen",
          path: "news",
          component: News,
          meta: { isAuth: true, title: "新闻" },
        },
        {
          name: "xiaoxi",
          path: "message",
          component: Message,
          meta: { isAuth: true, title: "消息" },
          children: [
            {
              name: "xiangqing",
              path: "detail",
              component: Detail,
              meta: { isAuth: true, title: "详情" },
              props($route) {
                return {
                  id: $route.query.id,
                  title: $route.query.title,
                };
              },
            },
          ],
        },
      ],
    },
  ],
});

//全局前置路由守卫：初始化时执行、每次路由切换前执行，调用的是一个函数（普通函数或箭头函数）
router.beforeEach((to, from, next) => {
  console.log("前置路由守卫", to, from);
  //判断是否需要鉴权
  if (to.meta.isAuth) {
    if (localStorage.getItem("school") === "atguigu") {
      next();
    } else {
      alert("学校名不对，无权限查看！");
    }
  } else {
    next();
  }
  /*  if (to.name === "xinwen" || to.name === "xiaoxi") {
    if (localStorage.getItem("school") === "atguigu") {
      next();
    } else {
      alert("学校名不对，无权限查看！");
    }
  } else {
    next();
  } */
});

 //全局后置路由守卫：初始化时执行、每次路由切换后执行
 router.afterEach((to, from) => {
  console.log("后置路由守卫", to, from);
  if (to.meta.title) {
    document.title = to.meta.title; //修改网页的title
  } else {
    document.title = "vue_test";
  }
});

export default router;
